package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.pojos.ApAssociateWords;
import com.heima.search.mapper.ApAssociateWordsMapper;
import com.heima.search.model.Trie;
import com.heima.search.service.ApAssociateWordsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ApAssociateWordsServiceImpl extends ServiceImpl<ApAssociateWordsMapper, ApAssociateWords> implements ApAssociateWordsService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public ResponseResult search(UserSearchDto dto) {

        //1.从缓存中获取数据
        String str = redisTemplate.opsForValue().get("associate_list");
        List<ApAssociateWords> apAssociateWords ;
        if (StringUtils.isNotEmpty(str)) {
            //2.缓存中存在，直接拿数据
            apAssociateWords = JSON.parseArray(str, ApAssociateWords.class);
        } else {
            //3.缓存中不存在，从数据库中获取数据，存储到redis
            apAssociateWords = list();
            redisTemplate.opsForValue().set("associate_list", JSON.toJSONString(apAssociateWords));
        }
        //4.构建trie数据结构，从trie中获取数据，封装返回
        Trie t = new Trie();
        for (ApAssociateWords apAssociateWord : apAssociateWords) {
            t.insert(apAssociateWord.getAssociateWords());
        }

        List<String> list = t.getData(dto.getSearchWords());

        if (list != null && !list.isEmpty()) {
            List<ApAssociateWords> resultList = new ArrayList<>();
            for (String keyWord : list) {
                ApAssociateWords aaw = new ApAssociateWords();
                aaw.setAssociateWords(keyWord);
                resultList.add(aaw);
            }

            return ResponseResult.okResult(resultList);
        }
        return ResponseResult.okResult();
    }

}